<template>
  <el-date-picker
    v-model="dateData"
    type="daterange"
    format="YYYY-MM-DD"
    placeholder="统计时间"
    start-placeholder="开始时间"
    end-placeholder="结束时间"
  ></el-date-picker>
  <div id="echarts-box"></div>
</template>
<script>
  import { getCurrentInstance, onMounted, reactive, ref, watch, computed } from 'vue';
  import { ElMessage } from 'element-plus';
  import Charts from '@/components/Charts.vue';

  import dayjs from 'dayjs';
  export default {
    setup() {
      const {
        $url: url,
        $service: service,
        JSON_HEADER: JSON_HEADER,
        $echarts: echarts,
      } = getCurrentInstance().appContext.config.globalProperties;
      // data
      const dateData = ref(null);
      const state = reactive({
        chartData: [],
        // 配置项
        option: {
          tooltip: {
            trigger: 'axis',
          },
          grid: {
            left: '3%',
            right: '3%',
            bottom: '3%',
            containLabel: true,
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          },
          yAxis: {
            type: 'value',
          },
          series: [
            {
              name: '累计推广总收益（元）',
              type: 'line',
              stack: '总量',
              data: [120, 132, 101, 134, 90, 230, 210],
            },
          ],
        },
      });

      watch(dateData, (newVal, oldVal) => {
        getData();
      });
      // methods
      // 得到数据
      const getData = () => {
        let startDate =
          dateData.value && dateData.value[0] instanceof Date
            ? dayjs(dateData.value[0]).format('YYYY-MM-DD')
            : '';
        let endDate =
          dateData.value && dateData.value[1] instanceof Date
            ? dayjs(dateData.value[1]).format('YYYY-MM-DD')
            : '';
        service.SaleIncomeDetail({ startDate: startDate, endDate: endDate }).then((res) => {
          state.chartData = res;
          initEcharts();
        });
      };
      // 初始化echarts
      const initEcharts = () => {
        // 基于准备好的dom，初始化echarts实例
        let myChart = echarts.init(document.getElementById('echarts-box'));
        let xData = [];
        let yData = [];
        state.chartData.forEach((item) => {
          xData.push(item.day);
          yData.push(item.saleAmount);
        });
        state.option.xAxis.data = xData;
        state.option.series[0].data = yData;
        myChart.setOption(state.option);
      };
      // life
      onMounted(() => {
        getData();
      });
      return {
        url,
        service,
        JSON_HEADER,
        echarts,
        // data
        dateData,
        state,
        // methods
        initEcharts,
        getData,
      };
    },
  };
</script>
<style scoped lang="less">
  #echarts-box {
    text-align: center;
    width: 600px;
    height: 390px;
  }
</style>
